<?php

include '../db.php';
$connect = pg_connect($connectionString);
if (!$connect) {
    echo "connect : A connection to the server could not be established!";
    return false;
}
$header = $_POST['header'];
$params = array();
array_push($params, pg_escape_string($header['emission_date']));
array_push($params, pg_escape_string($header['supplier_id']));
array_push($params, pg_escape_string($header['total']));
array_push($params, pg_escape_string($header['serie']));
array_push($params, pg_escape_string($header['number']));
array_push($params, pg_escape_string($header['cancellation_date']));
array_push($params, pg_escape_string($header['igv']));
array_push($params, pg_escape_string($header['subtotal']));

pg_query("BEGIN");
$stmt = pg_prepare($connect, "create_scaffold", "INSERT INTO purcharse_header(
            emission_date, supplier_id, total, serie, number, cancellation_date, 
            igv, subtotal)  VALUES ($1, $2, $3, $4, $5, $6, $7, $8);");
$result = pg_execute($connect, "create_scaffold", $params);

if (!$result) {
    die("Error in SQL query: " . pg_last_error());
}
$last_id_query = pg_query("SELECT currval('purcharse_header_id_seq')");

$last_id_results = pg_fetch_assoc($last_id_query);

$id_header = $last_id_results['currval'];
//------------------------------------------------------------------------------
$detail = $_POST['details'];

$stmt = pg_prepare($connect, "create_scaffold2", "INSERT INTO purcharse_detail(
             product_id, quantity, price, total,header_id)  VALUES ($1, $2, $3, $4, $5);");
$t = count($detail);
for ($i = 0; $i < $t; $i++) {
    $params = array();
    array_push($params, pg_escape_string($detail[$i]['id']));
    array_push($params, pg_escape_string($detail[$i]['quantity']));
    array_push($params, pg_escape_string($detail[$i]['price']));
    array_push($params, pg_escape_string($detail[$i]['total']));
    array_push($params, pg_escape_string($id_header));
    $result = pg_execute($connect, "create_scaffold2", $params);
}
pg_query("COMMIT");
pg_close($connect);




//echo json_encode($_POST['details']);